package stub

import (
	connect "connectrpc.com/connect"
	io "io"
)

import (
	"encoding/json"
	"errors"
	"gitee.com/filters/utils/logv"
	"github.com/rs/zerolog/log"
	"reflect"
	"strings"
	"time"
	"google.golang.org/protobuf/reflect/protoreflect"
	"context"
	"fmt"
	"net/http"
	"google.golang.org/protobuf/types/descriptorpb"
)

const _ = connect.IsAtLeastVersion1_13_0

const (
	// UserServiceName is the fully-qualified name of the UserService service.
	UserServiceName = "/approval.UserService/"
)

// These constants are the fully-qualified names of the RPCs defined in this package. They're
// exposed at runtime as Spec.Procedure and as the final two segments of the HTTP route.
//
// Note that these are different from the fully-qualified method names used by
// google.golang.org/protobuf/reflect/protoreflect. To convert from these constants to
// reflection-formatted method names, remove the leading slash and convert the remaining slash to a
// period.
const (
	// UserServiceUserProcedure is the fully-qualified name of the UserService's User RPC.
	UserServiceUserProcedure = "/approval.UserService/User"
	// UserServiceHelloProcedure is the fully-qualified name of the UserService's Hello RPC.
	UserServiceHelloProcedure = "/approval.UserService/Hello"
)

// UserServiceClient is a client for the approval.UserService service.
type UserServiceClient interface {
	User(context.Context, *connect.Request[UserRequest]) (*connect.Response[UserResponse], error)
	Hello(context.Context, *connect.Request[HelloReq]) (*connect.Response[HelloResp], error)
}

// NewUserServiceClient constructs a client for the approval.UserService service. By default, it
// uses the Connect protocol with the binary Protobuf Codec, asks for gzipped responses, and sends
// uncompressed requests. To use the gRPC or gRPC-Web protocols, supply the connect.WithGRPC() or
// connect.WithGRPCWeb() options.
//
// The URL supplied here should be the base URL for the Connect or gRPC server (for example,
// http://api.acme.com or https://acme.com/grpc).
func NewUserServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) UserServiceClient {
	baseURL = strings.TrimRight(baseURL, "/")
	return &userServiceClient{
		user: connect.NewClient[UserRequest, UserResponse](
			httpClient,
			baseURL+UserServiceUserProcedure,
			connect.WithSchema(GetUserServiceUserMethodDescriptor()),
			connect.WithClientOptions(opts...),
		),
		hello: connect.NewClient[HelloReq, HelloResp](
			httpClient,
			baseURL+UserServiceHelloProcedure,
			connect.WithSchema(GetUserServiceHelloMethodDescriptor()),
			connect.WithClientOptions(opts...),
		),
	}
}

// userServiceClient implements UserServiceClient.
type userServiceClient struct {
	user  *connect.Client[UserRequest, UserResponse]
	hello *connect.Client[HelloReq, HelloResp]
}

// User calls approval.UserService.User.
func (c *userServiceClient) User(ctx context.Context, req *connect.Request[UserRequest]) (*connect.Response[UserResponse], error) {
	return c.user.CallUnary(ctx, req)
}

// Hello calls approval.UserService.Hello.
func (c *userServiceClient) Hello(ctx context.Context, req *connect.Request[HelloReq]) (*connect.Response[HelloResp], error) {
	return c.hello.CallUnary(ctx, req)
}

// UserServiceHandler is an implementation of the approval.UserService service.
type UserServiceHandler interface {
	User(context.Context, *connect.Request[UserRequest]) (*connect.Response[UserResponse], error)
	Hello(context.Context, *connect.Request[HelloReq]) (*connect.Response[HelloResp], error)
}

// NewUserServiceHandler builds an HTTP handler from the service implementation. It returns the
// path on which to mount the handler and the handler itself.
//
// By default, handlers support the Connect, gRPC, and gRPC-Web protocols with the binary Protobuf
// and JSON codecs. They also support gzip compression.
func NewUserServiceHandler(svc UserServiceHandler, opts ...connect.HandlerOption) (string, http.Handler) {
	userserviceUserHandler := connect.NewUnaryHandler(
		UserServiceUserProcedure,
		svc.User,
		connect.WithSchema(GetUserServiceUserMethodDescriptor()),
		connect.WithHandlerOptions(opts...),
	)
	userserviceHelloHandler := connect.NewUnaryHandler(
		UserServiceHelloProcedure,
		svc.Hello,
		connect.WithSchema(GetUserServiceHelloMethodDescriptor()),
		connect.WithHandlerOptions(opts...),
	)
	return UserServiceName, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case UserServiceUserProcedure:
			userserviceUserHandler.ServeHTTP(w, r)
		case UserServiceHelloProcedure:
			userserviceHelloHandler.ServeHTTP(w, r)
		default:
			http.NotFound(w, r)
		}
	})
}

// UnimplementedUserServiceHandler returns CodeUnimplemented from all methods.
type UnimplementedUserServiceHandler struct{}

func (UnimplementedUserServiceHandler) User(context.Context, *connect.Request[UserRequest]) (*connect.Response[UserResponse], error) {
	return nil, connect.NewError(connect.CodeUnimplemented, errors.New("approval.UserService.User is not implemented"))
}

func (UnimplementedUserServiceHandler) Hello(context.Context, *connect.Request[HelloReq]) (*connect.Response[HelloResp], error) {
	return nil, connect.NewError(connect.CodeUnimplemented, errors.New("approval.UserService.Hello is not implemented"))
}

// 公共服务描述符，使用延迟初始化避免包初始化顺序问题
var (
	userserviceServiceDescriptor             protoreflect.ServiceDescriptor
	userserviceServiceUserMethodDescriptor   protoreflect.MethodDescriptor
	userserviceServiceHelloMethodDescriptor  protoreflect.MethodDescriptor
	userserviceServiceDescriptorsInitialized bool
)

// initUserServiceServiceDescriptors 初始化UserService服务描述符（延迟初始化）
func initUserServiceServiceDescriptors() {
	if !userserviceServiceDescriptorsInitialized {
		userserviceServiceDescriptor = File_hello_proto.Services().ByName("UserService")
		userserviceServiceUserMethodDescriptor = userserviceServiceDescriptor.Methods().ByName("User")
		userserviceServiceHelloMethodDescriptor = userserviceServiceDescriptor.Methods().ByName("Hello")
		userserviceServiceDescriptorsInitialized = true
	}
}

// GetUserServiceServiceDescriptor 获取UserService服务描述符
func GetUserServiceServiceDescriptor() protoreflect.ServiceDescriptor {
	initUserServiceServiceDescriptors()
	return userserviceServiceDescriptor
}

// GetUserServiceUserMethodDescriptor 获取UserServiceUser方法描述符
func GetUserServiceUserMethodDescriptor() protoreflect.MethodDescriptor {
	initUserServiceServiceDescriptors()
	return userserviceServiceUserMethodDescriptor
}

// GetUserServiceHelloMethodDescriptor 获取UserServiceHello方法描述符
func GetUserServiceHelloMethodDescriptor() protoreflect.MethodDescriptor {
	initUserServiceServiceDescriptors()
	return userserviceServiceHelloMethodDescriptor
}

// GetUserServiceFieldAnnotations 获取UserService服务字段注解信息
func GetUserServiceFieldAnnotations() map[string]map[string]string {
	annotations := make(map[string]map[string]string)
	serviceDesc := GetUserServiceServiceDescriptor()

	// User 输入消息字段注解
	if inputDesc := serviceDesc.Methods().ByName("User").Input(); inputDesc != nil {
		inputAnnotations := make(map[string]string)
		inputFields := inputDesc.Fields()
		for i := 0; i < inputFields.Len(); i++ {
			field := inputFields.Get(i)
			if options := field.Options().(*descriptorpb.FieldOptions); options != nil {
				// 这里可以根据需要提取特定的注解
				inputAnnotations[string(field.Name())] = fmt.Sprintf("字段: %s, 类型: %s", field.Name(), field.Kind().String())
			} else {
				inputAnnotations[string(field.Name())] = fmt.Sprintf("字段: %s, 类型: %s", field.Name(), field.Kind().String())
			}
		}
		annotations["UserRequest"] = inputAnnotations
	}

	// User 输出消息字段注解
	if outputDesc := serviceDesc.Methods().ByName("User").Output(); outputDesc != nil {
		outputAnnotations := make(map[string]string)
		outputFields := outputDesc.Fields()
		for i := 0; i < outputFields.Len(); i++ {
			field := outputFields.Get(i)
			if options := field.Options().(*descriptorpb.FieldOptions); options != nil {
				outputAnnotations[string(field.Name())] = fmt.Sprintf("字段: %s, 类型: %s", field.Name(), field.Kind().String())
			} else {
				outputAnnotations[string(field.Name())] = fmt.Sprintf("字段: %s, 类型: %s", field.Name(), field.Kind().String())
			}
		}
		annotations["UserResponse"] = outputAnnotations
	}

	// Hello 输入消息字段注解
	if inputDesc := serviceDesc.Methods().ByName("Hello").Input(); inputDesc != nil {
		inputAnnotations := make(map[string]string)
		inputFields := inputDesc.Fields()
		for i := 0; i < inputFields.Len(); i++ {
			field := inputFields.Get(i)
			if options := field.Options().(*descriptorpb.FieldOptions); options != nil {
				// 这里可以根据需要提取特定的注解
				inputAnnotations[string(field.Name())] = fmt.Sprintf("字段: %s, 类型: %s", field.Name(), field.Kind().String())
			} else {
				inputAnnotations[string(field.Name())] = fmt.Sprintf("字段: %s, 类型: %s", field.Name(), field.Kind().String())
			}
		}
		annotations["HelloRequest"] = inputAnnotations
	}

	// Hello 输出消息字段注解
	if outputDesc := serviceDesc.Methods().ByName("Hello").Output(); outputDesc != nil {
		outputAnnotations := make(map[string]string)
		outputFields := outputDesc.Fields()
		for i := 0; i < outputFields.Len(); i++ {
			field := outputFields.Get(i)
			if options := field.Options().(*descriptorpb.FieldOptions); options != nil {
				outputAnnotations[string(field.Name())] = fmt.Sprintf("字段: %s, 类型: %s", field.Name(), field.Kind().String())
			} else {
				outputAnnotations[string(field.Name())] = fmt.Sprintf("字段: %s, 类型: %s", field.Name(), field.Kind().String())
			}
		}
		annotations["HelloResponse"] = outputAnnotations
	}

	return annotations
}

// PrintUserServiceFieldAnnotations 打印UserService服务字段注解信息
func PrintUserServiceFieldAnnotations() {
	annotations := GetUserServiceFieldAnnotations()
	fmt.Println("\n📝 UserService 服务字段注解信息:")
	fmt.Println(strings.Repeat("=", 50))
	for msgType, fields := range annotations {
		fmt.Printf("\n📋 消息类型: %s\n", msgType)
		for fieldName, annotation := range fields {
			fmt.Printf("  🔸 %s: %s\n", fieldName, annotation)
		}
	}
	fmt.Println(strings.Repeat("=", 50))
}

// getUserServiceServiceDescriptor 内部使用的获取服务描述符函数
func getUserServiceServiceDescriptor() protoreflect.ServiceDescriptor {
	initUserServiceServiceDescriptors()
	return userserviceServiceDescriptor
}

// getUserServiceUserMethodDescriptor 内部使用的获取UserServiceUser方法描述符函数
func getUserServiceUserMethodDescriptor() protoreflect.MethodDescriptor {
	initUserServiceServiceDescriptors()
	return userserviceServiceUserMethodDescriptor
}

// getUserServiceHelloMethodDescriptor 内部使用的获取UserServiceHello方法描述符函数
func getUserServiceHelloMethodDescriptor() protoreflect.MethodDescriptor {
	initUserServiceServiceDescriptors()
	return userserviceServiceHelloMethodDescriptor
}

func NewUserServiceConnectxServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) UserServiceClient {
	baseURL = strings.TrimRight(baseURL, "/")
	return &userServiceClient{
		user: connect.NewClient[UserRequest, UserResponse](
			httpClient,
			baseURL+UserServiceUserProcedure,
			connect.WithSchema(GetUserServiceUserMethodDescriptor()),
			connect.WithClientOptions(opts...),
		),
		hello: connect.NewClient[HelloReq, HelloResp](
			httpClient,
			baseURL+UserServiceHelloProcedure,
			connect.WithSchema(GetUserServiceHelloMethodDescriptor()),
			connect.WithClientOptions(opts...),
		),
	}
}

// grcp转成http请求handler
func NewUserServiceConnectxServiceHandler(svc UserServiceHandler, opts ...connect.HandlerOption) (string, http.Handler) {
	user_ServerHandlerTemp := connect.NewUnaryHandler(
		UserServiceUserProcedure,
		svc.User,
		connect.WithSchema(GetUserServiceUserMethodDescriptor()),
		connect.WithHandlerOptions(opts...),
	)
	hello_ServerHandlerTemp := connect.NewUnaryHandler(
		UserServiceHelloProcedure,
		svc.Hello,
		connect.WithSchema(GetUserServiceHelloMethodDescriptor()),
		connect.WithHandlerOptions(opts...),
	)
	return UserServiceName, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 默认只支持POST方法
		if r.Method != POST {
			http.Error(w, "Method not allowed. Only POST is supported by default.", http.StatusMethodNotAllowed)
			return
		}
		switch r.URL.Path {
		case UserServiceUserProcedure:
			user_ServerHandlerTemp.ServeHTTP(w, r)
		case UserServiceHelloProcedure:
			hello_ServerHandlerTemp.ServeHTTP(w, r)
		default:
			http.NotFound(w, r)
		}
	})
}

// UserServiceServer is the standard gRPC server interface.
type UserServiceServer interface {
	User(context.Context, *UserRequest) (*UserResponse, error)
	Hello(context.Context, *HelloReq) (*HelloResp, error)
}

// ValidateUserServiceServerImplementation 检查服务器是否完全实现了UserServiceServer接口
func ValidateUserServiceServerImplementation(server UserServiceServer) error {
	if server == nil {
		return fmt.Errorf("UserServiceServer 不能为 nil")
	}

	// 使用类型断言检查接口实现
	serverType := reflect.TypeOf(server)
	interfaceType := reflect.TypeOf((*UserServiceServer)(nil)).Elem()

	// 检查是否实现了接口
	if !serverType.Implements(interfaceType) {
		return fmt.Errorf("类型 %s 没有完全实现 UserServiceServer 接口", serverType)
	}

	// 详细检查每个方法的实现
	missingMethods := []string{}
	if method, ok := serverType.MethodByName("User"); !ok {
		missingMethods = append(missingMethods, "User")
	} else {
		// 检查方法签名
		methodType := method.Type
		if methodType.NumIn() != 3 || methodType.NumOut() != 2 {
			missingMethods = append(missingMethods, "User (签名不正确)")
		}
	}
	if method, ok := serverType.MethodByName("Hello"); !ok {
		missingMethods = append(missingMethods, "Hello")
	} else {
		// 检查方法签名
		methodType := method.Type
		if methodType.NumIn() != 3 || methodType.NumOut() != 2 {
			missingMethods = append(missingMethods, "Hello (签名不正确)")
		}
	}

	if len(missingMethods) > 0 {
		return fmt.Errorf("UserServiceServer 缺少以下方法实现: %v", missingMethods)
	}

	fmt.Printf("✅ UserServiceServer 接口实现检查通过\n")
	return nil
}

type userServiceServiceServiceAdapter struct {
	server       UserServiceServer
	interceptors []Interceptor
}

func NewUserServiceServiceAdapter(server UserServiceServer) UserServiceHandler {
	return &userServiceServiceServiceAdapter{server: server, interceptors: []Interceptor{}}
}

func NewUserServiceServiceAdapterWithInterceptors(server UserServiceServer, interceptors ...Interceptor) UserServiceHandler {
	return &userServiceServiceServiceAdapter{server: server, interceptors: interceptors}
}

func (a *userServiceServiceServiceAdapter) runInterceptors(ctx context.Context, method string, req interface{}) (context.Context, error) {
	for _, interceptor := range a.interceptors {
		var err error
		ctx, err = interceptor.Intercept(ctx, method, req)
		if err != nil {
			return ctx, err
		}
	}
	return ctx, nil
}

func (a *userServiceServiceServiceAdapter) extractHeadersFromConnect(ctx context.Context, req interface{}) context.Context {
	switch r := req.(type) {
	case *connect.Request[UserRequest]:
		headers := make(map[string][]string)
		for key, values := range r.Header() {
			headers[strings.ToLower(key)] = values
		}
		return context.WithValue(ctx, "headers", headers)
	case *connect.Request[HelloReq]:
		headers := make(map[string][]string)
		for key, values := range r.Header() {
			headers[strings.ToLower(key)] = values
		}
		return context.WithValue(ctx, "headers", headers)
	}
	return ctx
}

func (a *userServiceServiceServiceAdapter) User(ctx context.Context, req *connect.Request[UserRequest]) (*connect.Response[UserResponse], error) {
	ctx = a.extractHeadersFromConnect(ctx, req)
	var err error
	ctx, err = a.runInterceptors(ctx, "User", req)
	if err != nil {
		return nil, err
	}
	grpcReq := req.Msg
	grpcResp, err := a.server.User(ctx, grpcReq)
	if err != nil {
		return nil, err
	}
	connectResp := connect.NewResponse(grpcResp)
	return connectResp, nil
}

func (a *userServiceServiceServiceAdapter) Hello(ctx context.Context, req *connect.Request[HelloReq]) (*connect.Response[HelloResp], error) {
	ctx = a.extractHeadersFromConnect(ctx, req)
	var err error
	ctx, err = a.runInterceptors(ctx, "Hello", req)
	if err != nil {
		return nil, err
	}
	grpcReq := req.Msg
	grpcResp, err := a.server.Hello(ctx, grpcReq)
	if err != nil {
		return nil, err
	}
	connectResp := connect.NewResponse(grpcResp)
	return connectResp, nil
}

// NewUserServiceHandlerWithMethodConfig 创建支持指定方法和HTTP方法的处理器
// 直接调用标准gRPC方法，HTTP和gRPC走同一套逻辑
func NewUserServiceHandlerWithMethodConfig(server UserServiceServer, interceptors []Interceptor, methodConfigs []MethodHTTPConfig, opts ...connect.HandlerOption) (string, http.Handler) {
	// 构建方法配置映射
	methodConfigMap := make(map[string]map[string]bool)
	for _, config := range methodConfigs {
		methodConfigMap[config.MethodName] = make(map[string]bool)
		for _, method := range config.AllowedMethods {
			methodConfigMap[config.MethodName][method] = true
		}
	}

	// 创建统一的方法处理器
	unifiedHandler := NewUnifiedUserServiceMethodHandler(server, interceptors)

	return UserServiceName, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 根据路径确定方法名
		var methodName string
		switch r.URL.Path {
		case UserServiceUserProcedure:
			methodName = "User"
		case UserServiceHelloProcedure:
			methodName = "Hello"
		default:
			http.NotFound(w, r)
			return
		}

		// 检查该方法是否支持当前HTTP方法
		if allowedMethods, exists := methodConfigMap[methodName]; exists {
			if !allowedMethods[r.Method] {
				allowedList := GetKeys(allowedMethods)
				http.Error(w, fmt.Sprintf("Method %s not allowed for %s. Allowed methods: %v",
					r.Method, methodName, allowedList), http.StatusMethodNotAllowed)
				return
			}
		} else {
			// 如果没有配置，默认只支持POST
			if r.Method != POST {
				http.Error(w, fmt.Sprintf("Method %s not allowed for %s. Only POST is supported by default.",
					r.Method, methodName), http.StatusMethodNotAllowed)
				return
			}
		}

		// 直接调用统一的方法处理器
		unifiedHandler.HandleRequest(w, r, methodName)
	})
}

// userServiceServiceAdapter adapts a standard gRPC server to the Connect handler interface.
type userServiceServiceAdapter struct {
	server       UserServiceServer
	interceptors []Interceptor
}

// NewUserServiceAdapter creates an adapter that converts standard gRPC methods to Connect handlers.
func NewUserServiceAdapter(server UserServiceServer) UserServiceHandler {
	return &userServiceServiceAdapter{server: server, interceptors: []Interceptor{}}
}

// NewUserServiceAdapterWithInterceptors creates an adapter with interceptors.
func NewUserServiceAdapterWithInterceptors(server UserServiceServer, interceptors ...Interceptor) UserServiceHandler {
	return &userServiceServiceAdapter{server: server, interceptors: interceptors}
}

// runInterceptors executes all interceptors in order.
func (a *userServiceServiceAdapter) runInterceptors(ctx context.Context, method string, req interface{}) (context.Context, error) {
	for _, interceptor := range a.interceptors {
		var err error
		ctx, err = interceptor.Intercept(ctx, method, req)
		if err != nil {
			return ctx, err
		}
	}
	return ctx, nil
}

// extractHeadersFromConnect extracts headers from Connect request and adds them to context.
func (a *userServiceServiceAdapter) extractHeadersFromConnect(ctx context.Context, req interface{}) context.Context {
	// Try to extract headers from Connect request
	switch r := req.(type) {
	case *connect.Request[UserRequest]:
		headers := make(map[string][]string)
		for key, values := range r.Header() {
			headers[strings.ToLower(key)] = values
		}
		return context.WithValue(ctx, "headers", headers)
	case *connect.Request[HelloReq]:
		headers := make(map[string][]string)
		for key, values := range r.Header() {
			headers[strings.ToLower(key)] = values
		}
		return context.WithValue(ctx, "headers", headers)
	}
	return ctx
}

// User adapts the standard gRPC User method to Connect format.
func (a *userServiceServiceAdapter) User(ctx context.Context, req *connect.Request[UserRequest]) (*connect.Response[UserResponse], error) {
	// Extract headers and add to context for interceptors
	ctx = a.extractHeadersFromConnect(ctx, req)

	// Run interceptors
	var err error
	ctx, err = a.runInterceptors(ctx, "User", req)
	if err != nil {
		return nil, err
	}

	// Convert Connect request to standard gRPC request
	grpcReq := req.Msg

	// Call the standard gRPC method
	grpcResp, err := a.server.User(ctx, grpcReq)
	if err != nil {
		return nil, err
	}

	// Convert standard gRPC response to Connect response
	connectResp := connect.NewResponse(grpcResp)
	return connectResp, nil
}

// Hello adapts the standard gRPC Hello method to Connect format.
func (a *userServiceServiceAdapter) Hello(ctx context.Context, req *connect.Request[HelloReq]) (*connect.Response[HelloResp], error) {
	// Extract headers and add to context for interceptors
	ctx = a.extractHeadersFromConnect(ctx, req)

	// Run interceptors
	var err error
	ctx, err = a.runInterceptors(ctx, "Hello", req)
	if err != nil {
		return nil, err
	}

	// Convert Connect request to standard gRPC request
	grpcReq := req.Msg

	// Call the standard gRPC method
	grpcResp, err := a.server.Hello(ctx, grpcReq)
	if err != nil {
		return nil, err
	}

	// Convert standard gRPC response to Connect response
	connectResp := connect.NewResponse(grpcResp)
	return connectResp, nil
}

// NewUserServiceHandlerWithHTTPMethods 创建支持多种HTTP方法的处理器
func NewUserServiceHandlerWithHTTPMethods(svc UserServiceHandler, opts ...connect.HandlerOption) (string, http.Handler) {
	// 获取原始的Connect处理器
	basePath, baseHandler := NewUserServiceHandler(svc, opts...)

	// 创建HTTP方法处理器
	methodHandler := NewDefaultHTTPMethodHandler(baseHandler)

	return basePath, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 记录请求信息
		log.Printf("HTTP %s request to %s", r.Method, r.URL.Path)

		// 根据HTTP方法分发请求
		switch r.Method {
		case GET:
			if err := methodHandler.HandleGET(w, r, r.URL.Path); err != nil {
				log.Printf("GET request error: %v", err)
			}
		case POST:
			if err := methodHandler.HandlePOST(w, r, r.URL.Path); err != nil {
				log.Printf("POST request error: %v", err)
			}
		case DELETE:
			if err := methodHandler.HandleDELETE(w, r, r.URL.Path); err != nil {
				log.Printf("DELETE request error: %v", err)
			}
		case PUT:
			if err := methodHandler.HandlePUT(w, r, r.URL.Path); err != nil {
				log.Printf("PUT request error: %v", err)
			}
		case OPTIONS:
			// 处理CORS预检请求
			w.Header().Set("Access-Control-Allow-Origin", "*")
			w.Header().Set("Access-Control-Allow-Methods", GET+", "+POST+", "+PUT+", "+DELETE+", "+OPTIONS)
			w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, x-token")
			w.WriteHeader(http.StatusOK)
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})
}

// NewUserServiceHandlerWithCustomHTTPMethods 创建自定义HTTP方法支持的处理器
func NewUserServiceHandlerWithCustomHTTPMethods(svc UserServiceHandler, config *HTTPMethodConfig, opts ...connect.HandlerOption) (string, http.Handler) {
	if config == nil {
		config = DefaultHTTPMethodConfig()
	}

	// 获取原始的Connect处理器
	basePath, baseHandler := NewUserServiceHandler(svc, opts...)

	// 创建HTTP方法处理器
	methodHandler := NewDefaultHTTPMethodHandler(baseHandler)

	return basePath, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 记录请求信息
		log.Printf("HTTP %s request to %s", r.Method, r.URL.Path)

		// 根据配置和HTTP方法分发请求
		switch r.Method {
		case GET:
			if config.EnableGET {
				if err := methodHandler.HandleGET(w, r, r.URL.Path); err != nil {
					log.Printf("GET request error: %v", err)
				}
			} else {
				http.Error(w, "GET method not allowed", http.StatusMethodNotAllowed)
			}
		case POST:
			if config.EnablePOST {
				if err := methodHandler.HandlePOST(w, r, r.URL.Path); err != nil {
					log.Printf("POST request error: %v", err)
				}
			} else {
				http.Error(w, "POST method not allowed", http.StatusMethodNotAllowed)
			}
		case DELETE:
			if config.EnableDELETE {
				if err := methodHandler.HandleDELETE(w, r, r.URL.Path); err != nil {
					log.Printf("DELETE request error: %v", err)
				}
			} else {
				http.Error(w, "DELETE method not allowed", http.StatusMethodNotAllowed)
			}
		case PUT:
			if config.EnablePUT {
				if err := methodHandler.HandlePUT(w, r, r.URL.Path); err != nil {
					log.Printf("PUT request error: %v", err)
				}
			} else {
				http.Error(w, "PUT method not allowed", http.StatusMethodNotAllowed)
			}
		case OPTIONS:
			if config.EnableCORS {
				// 处理CORS预检请求
				w.Header().Set("Access-Control-Allow-Origin", "*")
				w.Header().Set("Access-Control-Allow-Methods", GET+", "+POST+", "+PUT+", "+DELETE+", "+OPTIONS)
				w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, x-token")
				w.WriteHeader(http.StatusOK)
			} else {
				http.Error(w, "OPTIONS method not allowed", http.StatusMethodNotAllowed)
			}
		default:
			http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		}
	})
}

// UnifiedUserServiceMethodHandler 统一的方法处理器，HTTP和gRPC走同一套逻辑
type UnifiedUserServiceMethodHandler struct {
	server       UserServiceServer
	interceptors []Interceptor
}

// NewUnifiedUserServiceMethodHandler 创建统一方法处理器
func NewUnifiedUserServiceMethodHandler(server UserServiceServer, interceptors []Interceptor) *UnifiedUserServiceMethodHandler {
	return &UnifiedUserServiceMethodHandler{
		server:       server,
		interceptors: interceptors,
	}
}

// HandleRequest 处理HTTP请求，直接调用gRPC方法
func (h *UnifiedUserServiceMethodHandler) HandleRequest(w http.ResponseWriter, r *http.Request, methodName string) {
	ctx := r.Context()

	// 从context中提取trace_id
	traceID := ""
	if tid := ctx.Value("trace_id"); tid != nil {
		if tidStr, ok := tid.(string); ok {
			traceID = tidStr
		}
	}
	// 如果没有从context获取到，尝试从logv获取
	if traceID == "" {
		traceID = logv.GetTraceID(ctx)
	}
	// 如果还是没有，尝试从HTTP头获取
	if traceID == "" {
		traceID = r.Header.Get("X-Trace-ID")
	}

	// 提取HTTP headers并添加到context
	headers := make(map[string][]string)
	for key, values := range r.Header {
		headers[strings.ToLower(key)] = values
	}
	ctx = context.WithValue(ctx, "headers", headers)
	// 确保trace_id在context中
	if traceID != "" {
		ctx = context.WithValue(ctx, "trace_id", traceID)
	}

	// 运行拦截器
	for _, interceptor := range h.interceptors {
		var err error
		ctx, err = interceptor.Intercept(ctx, methodName, nil)
		if err != nil {
			// 处理Connect错误
			if connectErr, ok := err.(*connect.Error); ok {
				switch connectErr.Code() {
				case connect.CodeUnauthenticated:
					h.writeErrorResponse(w, "UNAUTHORIZED", "认证失败", connectErr.Message(), http.StatusUnauthorized, traceID)
				case connect.CodePermissionDenied:
					h.writeErrorResponse(w, "FORBIDDEN", "权限不足", connectErr.Message(), http.StatusForbidden, traceID)
				default:
					h.writeErrorResponse(w, "INTERNAL_ERROR", "内部错误", connectErr.Message(), http.StatusInternalServerError, traceID)
				}
			} else {
				h.writeErrorResponse(w, "INTERNAL_ERROR", "内部服务器错误", err.Error(), http.StatusInternalServerError, traceID)
			}
			return
		}
	}

	// 解析请求参数
	var requestData map[string]interface{}

	if r.Method == GET {
		// GET请求从查询参数中获取数据
		requestData = make(map[string]interface{})
		for key, values := range r.URL.Query() {
			if len(values) == 1 {
				requestData[key] = values[0]
			} else {
				requestData[key] = values
			}
		}
	} else {
		// POST/PUT/DELETE请求从请求体中获取JSON数据
		// 先检查请求体是否为空
		if r.ContentLength == 0 || r.Body == nil {
			// 空请求体，初始化为空map
			requestData = make(map[string]interface{})
		} else {
			// 尝试解析JSON
			decoder := json.NewDecoder(r.Body)
			if err := decoder.Decode(&requestData); err != nil {
				// 如果是EOF错误（空body），初始化为空map
				if err == io.EOF {
					requestData = make(map[string]interface{})
				} else {
					h.writeErrorResponse(w, "INVALID_JSON", "JSON格式错误", err.Error(), http.StatusBadRequest, traceID)
					return
				}
			}
		}
	}

	// 根据方法名调用对应的gRPC方法
	switch methodName {
	case "User":
		h.handleUser(ctx, w, requestData)
	case "Hello":
		h.handleHello(ctx, w, requestData)
	default:
		http.Error(w, "Method not found", http.StatusNotFound)
	}
}

// handleUser 处理User方法
func (h *UnifiedUserServiceMethodHandler) handleUser(ctx context.Context, w http.ResponseWriter, requestData map[string]interface{}) {
	// 从context中提取trace_id
	traceID := ""
	if tid := ctx.Value("trace_id"); tid != nil {
		if tidStr, ok := tid.(string); ok {
			traceID = tidStr
		}
	}
	// 如果没有从context获取到，尝试从logv获取
	if traceID == "" {
		traceID = logv.GetTraceID(ctx)
	}

	// 构造gRPC请求
	req := &UserRequest{}

	// 动态映射请求数据到protobuf结构体
	if err := h.mapRequestDataToProto(requestData, req); err != nil {
		log.Error().Str("trace_id", traceID).Err(err).Msg("请求数据映射失败")
		h.writeErrorResponse(w, "INVALID_REQUEST_DATA", "请求数据格式错误", err.Error(), http.StatusBadRequest, traceID)
		return
	}

	// 直接调用标准gRPC方法
	resp, err := h.server.User(ctx, req)
	if err != nil {
		log.Error().Str("trace_id", traceID).Err(err).Msg("gRPC方法执行失败")
		h.writeErrorResponse(w, "GRPC_ERROR", "gRPC方法执行失败", err.Error(), http.StatusInternalServerError, traceID)
		return
	}

	// 记录响应结果
	log.Debug().Str("trace_id", traceID).Interface("response", resp).Msg("gRPC响应结果")

	// 返回JSON响应
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("X-Trace-ID", traceID) // 将trace_id添加到响应头
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		log.Error().Str("trace_id", traceID).Err(err).Msg("响应编码失败")
		h.writeErrorResponse(w, "RESPONSE_ENCODE_ERROR", "响应编码失败", err.Error(), http.StatusInternalServerError, traceID)
	}
}

// handleHello 处理Hello方法
func (h *UnifiedUserServiceMethodHandler) handleHello(ctx context.Context, w http.ResponseWriter, requestData map[string]interface{}) {
	// 从context中提取trace_id
	traceID := ""
	if tid := ctx.Value("trace_id"); tid != nil {
		if tidStr, ok := tid.(string); ok {
			traceID = tidStr
		}
	}
	// 如果没有从context获取到，尝试从logv获取
	if traceID == "" {
		traceID = logv.GetTraceID(ctx)
	}

	// 构造gRPC请求
	req := &HelloReq{}

	// 动态映射请求数据到protobuf结构体
	if err := h.mapRequestDataToProto(requestData, req); err != nil {
		log.Error().Str("trace_id", traceID).Err(err).Msg("请求数据映射失败")
		h.writeErrorResponse(w, "INVALID_REQUEST_DATA", "请求数据格式错误", err.Error(), http.StatusBadRequest, traceID)
		return
	}

	// 直接调用标准gRPC方法
	resp, err := h.server.Hello(ctx, req)
	if err != nil {
		log.Error().Str("trace_id", traceID).Err(err).Msg("gRPC方法执行失败")
		h.writeErrorResponse(w, "GRPC_ERROR", "gRPC方法执行失败", err.Error(), http.StatusInternalServerError, traceID)
		return
	}

	// 记录响应结果
	log.Debug().Str("trace_id", traceID).Interface("response", resp).Msg("gRPC响应结果")

	// 返回JSON响应
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("X-Trace-ID", traceID) // 将trace_id添加到响应头
	if err := json.NewEncoder(w).Encode(resp); err != nil {
		log.Error().Str("trace_id", traceID).Err(err).Msg("响应编码失败")
		h.writeErrorResponse(w, "RESPONSE_ENCODE_ERROR", "响应编码失败", err.Error(), http.StatusInternalServerError, traceID)
	}
}

// writeErrorResponse 写入自定义JSON错误响应
func (h *UnifiedUserServiceMethodHandler) writeErrorResponse(w http.ResponseWriter, code string, message string, detail string, httpStatus int, traceID string) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("X-Trace-ID", traceID)
	w.WriteHeader(httpStatus)

	// 尝试从错误详情中解析ret或code状态码
	retCode := -2000 // 默认错误码

	// 尝试解析JSON格式的错误信息
	var errorData map[string]interface{}
	if err := json.Unmarshal([]byte(detail), &errorData); err == nil {
		// 优先查找ret字段
		if ret, ok := errorData["ret"]; ok {
			if retInt, ok := ret.(float64); ok {
				retCode = int(retInt)
			} else if retStr, ok := ret.(string); ok {
				if parsedRet, err := fmt.Sscanf(retStr, "%d"); err == nil && parsedRet == 1 {
					var tempRet int
					fmt.Sscanf(retStr, "%d", &tempRet)
					retCode = tempRet
				}
			}
		} else if code, ok := errorData["code"]; ok {
			// 如果没有ret字段，查找code字段
			if codeInt, ok := code.(float64); ok {
				retCode = int(codeInt)
			} else if codeStr, ok := code.(string); ok {
				if parsedCode, err := fmt.Sscanf(codeStr, "%d"); err == nil && parsedCode == 1 {
					var tempCode int
					fmt.Sscanf(codeStr, "%d", &tempCode)
					retCode = tempCode
				}
			}
		}
	}

	// 如果没有从错误中解析到状态码，使用默认的错误类型映射
	if retCode == -2000 {
		switch code {
		case "UNAUTHORIZED":
			retCode = -2001
		case "FORBIDDEN":
			retCode = -2002
		case "INVALID_JSON":
			retCode = -2003
		case "INVALID_REQUEST_DATA":
			retCode = -2004
		case "GRPC_ERROR":
			retCode = -2005
		case "RESPONSE_ENCODE_ERROR":
			retCode = -2006
		}
	}

	errorResponse := map[string]interface{}{
		"ret":       retCode,
		"data":      "",
		"msg":       message + ": " + detail,
		"trace_id":  traceID,
		"timestamp": time.Now().Format(time.RFC3339),
	}

	if err := json.NewEncoder(w).Encode(errorResponse); err != nil {
		log.Error().Str("trace_id", traceID).Err(err).Msg("错误响应编码失败")
	}
}

// mapRequestDataToProto 将请求数据映射到protobuf结构体
func (h *UnifiedUserServiceMethodHandler) mapRequestDataToProto(requestData map[string]interface{}, target interface{}) error {
	if requestData == nil || target == nil {
		return nil
	}

	// 使用反射获取目标结构体的信息
	targetValue := reflect.ValueOf(target)
	if targetValue.Kind() != reflect.Ptr || targetValue.Elem().Kind() != reflect.Struct {
		return errors.New("target must be a pointer to struct")
	}

	targetStruct := targetValue.Elem()
	targetType := targetStruct.Type()

	// 遍历结构体的所有字段
	for i := 0; i < targetStruct.NumField(); i++ {
		field := targetStruct.Field(i)
		fieldType := targetType.Field(i)

		// 跳过不可设置的字段
		if !field.CanSet() {
			continue
		}

		// 获取字段名（支持json tag）
		fieldName := fieldType.Name
		if jsonTag := fieldType.Tag.Get("json"); jsonTag != "" {
			if commaIdx := strings.Index(jsonTag, ","); commaIdx > 0 {
				fieldName = jsonTag[:commaIdx]
			} else {
				fieldName = jsonTag
			}
		}

		// 将字段名转换为小写进行匹配（支持驼峰和下划线）
		possibleKeys := []string{
			fieldName,
			strings.ToLower(fieldName),
			strings.ToLower(fieldType.Name),
		}

		// 尝试从请求数据中找到对应的值
		var value interface{}
		var found bool
		for _, key := range possibleKeys {
			if v, ok := requestData[key]; ok {
				value = v
				found = true
				break
			}
		}

		if !found {
			continue
		}

		// 根据字段类型设置值
		if err := h.setFieldValue(field, value); err != nil {
			return fmt.Errorf("failed to set field %s: %w", fieldType.Name, err)
		}
	}

	return nil
}

// setFieldValue 设置字段值
func (h *UnifiedUserServiceMethodHandler) setFieldValue(field reflect.Value, value interface{}) error {
	if value == nil {
		return nil
	}

	fieldType := field.Type()
	valueType := reflect.TypeOf(value)

	// 如果类型完全匹配，直接设置
	if valueType == fieldType {
		field.Set(reflect.ValueOf(value))
		return nil
	}

	// 类型转换
	switch fieldType.Kind() {
	case reflect.String:
		if str, ok := value.(string); ok {
			field.SetString(str)
		} else {
			field.SetString(fmt.Sprintf("%v", value))
		}

	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		switch v := value.(type) {
		case int:
			field.SetInt(int64(v))
		case int32:
			field.SetInt(int64(v))
		case int64:
			field.SetInt(v)
		case float64:
			field.SetInt(int64(v))
		case string:
			if intVal, err := fmt.Sscanf(v, "%d"); err == nil && intVal == 1 {
				var i int64
				fmt.Sscanf(v, "%d", &i)
				field.SetInt(i)
			} else {
				return fmt.Errorf("cannot convert string %s to int", v)
			}
		default:
			return fmt.Errorf("cannot convert %T to int", value)
		}

	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		switch v := value.(type) {
		case uint:
			field.SetUint(uint64(v))
		case uint32:
			field.SetUint(uint64(v))
		case uint64:
			field.SetUint(v)
		case int:
			if v >= 0 {
				field.SetUint(uint64(v))
			} else {
				return fmt.Errorf("cannot convert negative int to uint")
			}
		case float64:
			if v >= 0 {
				field.SetUint(uint64(v))
			} else {
				return fmt.Errorf("cannot convert negative float to uint")
			}
		default:
			return fmt.Errorf("cannot convert %T to uint", value)
		}

	case reflect.Float32, reflect.Float64:
		switch v := value.(type) {
		case float32:
			field.SetFloat(float64(v))
		case float64:
			field.SetFloat(v)
		case int:
			field.SetFloat(float64(v))
		case int64:
			field.SetFloat(float64(v))
		default:
			return fmt.Errorf("cannot convert %T to float", value)
		}

	case reflect.Bool:
		switch v := value.(type) {
		case bool:
			field.SetBool(v)
		case string:
			if b, err := fmt.Sscanf(v, "%t"); err == nil && b == 1 {
				var boolVal bool
				fmt.Sscanf(v, "%t", &boolVal)
				field.SetBool(boolVal)
			} else {
				return fmt.Errorf("cannot convert string %s to bool", v)
			}
		default:
			return fmt.Errorf("cannot convert %T to bool", value)
		}

	case reflect.Slice:
		// 处理切片类型
		if arr, ok := value.([]interface{}); ok {
			newSlice := reflect.MakeSlice(fieldType, len(arr), len(arr))
			for i, item := range arr {
				if err := h.setFieldValue(newSlice.Index(i), item); err != nil {
					return fmt.Errorf("failed to set slice element %d: %w", i, err)
				}
			}
			field.Set(newSlice)
		} else {
			return fmt.Errorf("cannot convert %T to slice", value)
		}

	default:
		// 对于其他复杂类型，尝试JSON序列化/反序列化
		jsonBytes, err := json.Marshal(value)
		if err != nil {
			return fmt.Errorf("failed to marshal value: %w", err)
		}

		newValue := reflect.New(fieldType)
		if err := json.Unmarshal(jsonBytes, newValue.Interface()); err != nil {
			return fmt.Errorf("failed to unmarshal to field type: %w", err)
		}

		field.Set(newValue.Elem())
	}

	return nil
}

// UserService 添加UserService服务
func (sc *ServiceChain) UserService(server UserServiceServer, methodConfigs []MethodHTTPConfig) *ServiceChain {
	// 检查服务器接口实现
	if err := ValidateUserServiceServerImplementation(server); err != nil {
		panic(fmt.Sprintf("❌ UserService服务接口实现检查失败: %v", err))
	}

	path, handler := NewUserServiceHandlerWithMethodConfig(server, sc.interceptors, methodConfigs)
	// 包装handler以添加请求日志和CORS支持
	wrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		sc.logRequest(r)
		handler.ServeHTTP(w, r)
	})
	// 应用CORS中间件
	finalHandler := sc.corsMiddleware(wrappedHandler)
	sc.mux.Handle(path, finalHandler)

	// 构建方法配置映射
	methodConfigMap := make(map[string][]string)
	for _, config := range methodConfigs {
		methodConfigMap[config.MethodName] = config.AllowedMethods
	}

	// 收集服务方法信息
	methods := []MethodInfo{
		{
			Name:          "User",
			ProcedurePath: UserServiceUserProcedure,
			SupportedMethods: func() []string {
				if configMethods, exists := methodConfigMap["User"]; exists {
					return configMethods
				} else {
					return []string{POST} // 默认只支持POST
				}
			}(),
		},
		{
			Name:          "Hello",
			ProcedurePath: UserServiceHelloProcedure,
			SupportedMethods: func() []string {
				if configMethods, exists := methodConfigMap["Hello"]; exists {
					return configMethods
				} else {
					return []string{POST} // 默认只支持POST
				}
			}(),
		},
	}

	// 添加到服务列表
	sc.services = append(sc.services, ServiceInfo{
		ServiceName: "UserService",
		Methods:     methods,
		BasePath:    path,
	})

	fmt.Printf("✅ 已注册 UserService 服务: %s\n", path)
	return sc
}
